from django.db import models
import django.contrib.auth.models

import logging

# Get an instance of a logger
#logger = logging.getLogger(__name__)

def jours_de_distribution(debut, fin, jour):
    import datetime

    if (debut.isoweekday() != jour or fin.isoweekday() != jour) :
        logging.error("pb with jours_de_distribution : debut=%s(%d), fin=%s(%d)" % (debut, debut.isoweekday(), fin, fin.isoweekday()))
        return None
    jours = []
    j = debut
    while j <= fin:
        jours.append(j)
        j = j + datetime.timedelta(7)
    return jours

# Create your models here.
class User(models.Model):
    user        = models.OneToOneField(django.contrib.auth.models.User)
    telephones  = models.CharField(max_length=50)
    addresse	= models.CharField(max_length=250)
    def __unicode__(self):
        return self.user.username

class Participant(models.Model):
    user        = models.ManyToManyField(User)
    groupes     = models.ManyToManyField('Group')
    debut       = models.DateField()
    fin         = models.DateField()
    types_paniers = models.ManyToManyField('TypePanier')
    
    def __unicode__(self):
        return '_'.join([x.user.username for x in self.user.iterator()])
        #return self.user.username

class Group(models.Model):
    JOURS=(
        (1, 'Lundi'),
        (2, 'Mardi'),
        (3, 'Mercredi'),
        (4, 'Jeudi'),
        (5, 'Vendredi'),
        (6, 'Samedi'),
        (7, 'Dimanche'),
    )
    nom 		= models.CharField(max_length=50)
    types_paniers	= models.ManyToManyField('TypePanier')
    jour_de_distribution = models.IntegerField(choices=JOURS, default=5)
    distrib		= models.BooleanField()
#   participants = models.ManyToManyField('Participant')
    
    def __unicode__(self):
        return self.nom

class TypePanier(models.Model):
    nom		= models.CharField(max_length=50)
    annee       = models.IntegerField()
    debut       = models.DateField()
    fin         = models.DateField()
#    fin_periode = models.DateField()
#    nombre      = models.IntegerField()
    
    def __unicode__(self):
        return self.nom+'-'+str(self.annee)
     
class Jour(models.Model):
    ETATS=(
        (1, 'Disponible'),
        (2, 'Indisponible'),
        (3, 'Participation'),
    )
    date        = models.DateField()
    #group       = models.ForeignKey('Group')
    participant = models.ForeignKey('Participant')
    etat        = models.IntegerField(choices=ETATS, default=1)
    panier	= models.BooleanField()
    def __unicode__(self):
        return str(self.participant)+'-'+str(self.date)

class Distribution(models.Model):
    date        = models.DateField()
    group       = models.ForeignKey('Group')
    participant = models.ForeignKey('Participant')
     
    def __unicode__(self):
        return str(self.group)+'-'+str(self.date)
   